package src.cs2340.todoApp;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class MapsActivity extends MapActivity 
{    
	MapView mapView; 
	private String username;
	private String password;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
	    	username = extras.getString("username");
	    	password = extras.getString("password");
	    }
		
		Account currAccount = new Account(username, password, null, null, Database.getInstance());
		currAccount = Database.getInstance().getUpdate(currAccount);
		
		mapView = (MapView) findViewById(R.id.mapView);
		LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);  
		View zoomView = mapView.getZoomControls(); 

		zoomLayout.addView(zoomView, 
				new LinearLayout.LayoutParams(
						android.view.ViewGroup.LayoutParams.WRAP_CONTENT, 
						android.view.ViewGroup.LayoutParams.WRAP_CONTENT)); 
		mapView.displayZoomControls(true);

		List<Overlay> mapOverlays = mapView.getOverlays();
		Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
		ToDoMapOverlay itemizedoverlay = new ToDoMapOverlay(drawable, this);
		
		Geocoder geocoder = new Geocoder(this, Locale.getDefault());
		int numLocs = 0;
		long avgLat = 0;
		long avgLng = 0;
		for (TaskItem item : currAccount.tasksList) {
			Log.e("MapsActivity","Item: "+item);
			Log.e("MapsActivity","Location: "+item.getLocation());
			String address = item.getLocation().getAddress();
			Log.e("MapsActivity", "Displaying marker at address: "+address);
			double[] coords = getLatLong(getLocationInfo(address));
			if (coords != null) {
				numLocs++;
				Log.e("MapsActivity", "Lat: "+coords[0] + " Lng: "+coords[1]);
				GeoPoint point = new GeoPoint((int)(coords[0]*1e6),(int)(coords[1]*1e6));
				avgLat += (int)(coords[0]*1e6);
				avgLng += (int)(coords[1]*1e6);
				OverlayItem overlayitem = new OverlayItem(point, item.getLocation().toString(), "");
				itemizedoverlay.addOverlay(overlayitem);
//				mapView.getController().setCenter(point);
			}
//			try {
//				Log.e("MapsActivity","Before getFromLocationName");
//				List<Address> addressResult = geocoder.getFromLocationName(address, 1);
//				Log.e("MapsActivity","After getFromLocationName");
//				if (!addressResult.isEmpty()) {
//					Log.e("MapsActivity","Inside if");
//					Address resultAddress = addressResult.get(0);
//					Log.e("MapsActivity", "Lat: "+resultAddress.getLatitude()+" Long: "+resultAddress.getLongitude());
//					GeoPoint point = new GeoPoint((int)(resultAddress.getLatitude()*1e6), (int)(resultAddress.getLongitude()*1e6));
//					OverlayItem overlayitem = new OverlayItem(point, item.getLocation().toString(), "");
//					itemizedoverlay.addOverlay(overlayitem);
//					mapView.getController().setCenter(point);
//				}
//			} catch (IOException e) {
//				Log.e("MapsActivity", "IOException occurred while parsing "+address);
//				e.printStackTrace();
//			}

		}
		int lat = (int)((double)avgLat/numLocs);
		int lng = (int)((double)avgLng/numLocs);
		GeoPoint point = new GeoPoint(lat, lng);
		mapView.getController().setCenter(point);
        mapOverlays.add(itemizedoverlay);		
//		GeoPoint point = new GeoPoint(33777249,-84403855);
//        OverlayItem overlayitem = new OverlayItem(point, "", "");
//        itemizedoverlay.addOverlay(overlayitem);
//
//        GeoPoint point2 = new GeoPoint(33771094,-84391823);
//        OverlayItem overlayitem2 = new OverlayItem(point2, "", "");
//        itemizedoverlay.addOverlay(overlayitem2);


//		GeoPoint point = new GeoPoint(19240000,-99120000);
//		OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
		
//		itemizedoverlay.addOverlay(overlayitem);
//		mapOverlays.add(itemizedoverlay);
//		mapView.getController().setCenter(point);
		
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	public double[] getLatLong(JSONObject jsonObject) {

		double[] ret = null;
        try {
            double longitute = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lng");

            double latitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lat");
            ret = new double[2];
            ret[0] = latitude;
            ret[1] = longitute;
        } catch (JSONException e) {
            return null;
        }
        return ret;
    }
	
	public JSONObject getLocationInfo(String address) {
        StringBuilder stringBuilder = new StringBuilder();
        try {

        address = address.replaceAll(" ","%20");    

        HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();


            response = client.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(stringBuilder.toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonObject;
    }
}